import { StyleSheet, Text, View, TouchableOpacity, ScrollView, Pressable, DeviceEventEmitter } from 'react-native';
import React, { useEffect, useState } from 'react';
import { useTranslation } from 'react-i18next';
import FastImage from '@d11/react-native-fast-image';
import Icon from 'react-native-vector-icons/Ionicons';
import { useCameraPermission } from 'react-native-vision-camera';
import { useNavigation, useRoute } from '@react-navigation/native';
import { NavBarHeader } from '~/components';
import { deviceStore, observer, userStore, webSocketStore } from '~/store';
import { checkAndRequestLocationPermissions, checkAndRequestBluetoothPermissions } from '~/utils/permission';
import { onePx, px2dp, scale } from '~/utils/px2dp';
import { getWuXueCourseApi, getDeviceBindBodyList, checkDeviceWriteApi, getUserUseTitleIdApi } from '~/api/acupoints';
import { getUserArticleListApi } from '~/api/deviceApi';
import BleConnection from '~/utils/ble/connect';
import { byBlewriteDevice } from './WriteCourse';
import SelectCourseModal from '../Acupoints/components/SelectCourseModal';
import UserDeviceListModal from './components/UserDeviceListModal';

const Bleconnect = BleConnection.getInstance();
export default observer(() => {
    const { deviceList } = webSocketStore;
    const { t } = useTranslation();
    const router = useRoute<any>();
    const { device_sn = '' } = router.params || {};
    const matchedDevice = userStore.userDeviceYY01Data.find((device) => device.device_sn == device_sn) || {
        device_sn: '',
        id: '',
    };
    const [title_id, setTitle_id] = useState(0);
    const navigation = useNavigation<any>();
    const [selectDevice, setSelecDevice] = useState<any>(matchedDevice); // 选中的YY01设备
    const { hasPermission, requestPermission } = useCameraPermission();
    const listData = [
        {
            id: 1,
            name: t('AddDeviceScreen.t15'),
            user_id: '',
            device_id: '',
            body_index: 1,
            armarium_device_chang: '',
            course_id: '',
            status: 0,
            device_image: 'https://bjy-crmeb.oss-cn-shenzhen.aliyuncs.com/attach/2024/06/ab18d20240619155430143.png',
            user_course_id: '',
        },
        {
            id: 2,
            name: t('AddDeviceScreen.t16'),
            user_id: '',
            device_id: '',
            body_index: 2,
            armarium_device_chang: '',
            course_id: '',
            status: 0,
            device_image: 'https://bjy-crmeb.oss-cn-shenzhen.aliyuncs.com/attach/2024/06/ab18d20240619155430143.png',
            user_course_id: '',
        },
        {
            id: 3,
            name: t('AddDeviceScreen.t17'),
            user_id: '',
            device_id: '',
            body_index: 3,
            armarium_device_chang: '',
            course_id: '',
            status: 0,
            device_image: 'https://bjy-crmeb.oss-cn-shenzhen.aliyuncs.com/attach/2024/06/ab18d20240619155430143.png',
            user_course_id: '',
        },
        {
            id: 4,
            name: t('AddDeviceScreen.t18'),
            user_id: '',
            device_id: '',
            body_index: 4,
            armarium_device_chang: '',
            course_id: '',
            status: 0,
            device_image: 'https://bjy-crmeb.oss-cn-shenzhen.aliyuncs.com/attach/2024/06/ab18d20240619155430143.png',
            user_course_id: '',
        },
        {
            id: 5,
            name: t('AddDeviceScreen.t19'),
            user_id: '',
            device_id: '',
            body_index: 5,
            armarium_device_chang: '',
            course_id: '',
            status: 0,
            device_image: 'https://bjy-crmeb.oss-cn-shenzhen.aliyuncs.com/attach/2024/06/ab18d20240619155430143.png',
            user_course_id: '',
        },
    ];

    // 获取已经绑定的设备列表
    const getBindList = async (id) => {
        const { isBleWriteCorse = '', subDeviceSn = '' } = router.params || {}; // 扫码返回对应的子设备
        try {
            if (id == 0) {
                webSocketStore.singDevices(listData);
                return;
            }
            const res = await getDeviceBindBodyList({ title_id: id });
            if (res.list.length === 0) {
                webSocketStore.singDevices(listData);
                return;
            }
            const list = Array.isArray(res?.list) ? res.list : [];
            const bindMap = new Map(list.map((item) => [String(item.body_index), item]));
            const updatedList = listData.map((itemB) => {
                const matchedItem: any = bindMap.get(String(itemB.body_index));
                return matchedItem
                    ? {
                          ...itemB,
                          id: matchedItem.id || itemB.id,
                          device_id: matchedItem.device_id || '',
                          user_id: matchedItem.user_id || '',
                          armarium_device_chang: matchedItem.armarium_device_chang || '',
                          course_id: matchedItem.course_id || '',
                          device_image: matchedItem.device_image || itemB.device_image,
                          user_course_id: matchedItem.user_course_id || '',
                          status: 0,
                      }
                    : itemB;
            });
            const newArray = updatedList.map(({ course_id, device_id }) => ({ course_id, device_id }));
            const result = await checkDeviceWriteApi({ json: JSON.stringify(newArray), title_id: id });
            const statusMap = Object.fromEntries(result.returnData.map((item) => [item.deviceId, item.courseStatus]));
            updatedList.forEach((device) => {
                device.status = statusMap[device.device_id] == '1' ? 1 : 0;
            });
            webSocketStore.singDevices(updatedList);
            // 开始写入疗程
            if (isBleWriteCorse == 'isBleWriteCorse') {
                const info: any = updatedList.find((item: any) => {
                    return item.armarium_device_chang == subDeviceSn;
                });
                const res = await byBlewriteDevice(info, 'start');
            }
        } catch (err) {
            webSocketStore.singDevices(listData);
        }
    };
    // 获取用户大包id
    const getTitleId = async () => {
        const result = await getUserUseTitleIdApi();
        setTitle_id(result.returnData); // 拿到大包id
        await getBindList(result.returnData);
    };
    useEffect(() => {
        const writeSuccessListener = DeviceEventEmitter.addListener('writeSuccess', (res) => {
            getTitleId();
        });
        return () => {
            writeSuccessListener.remove();
        };
    }, []);

    useEffect(() => {
        if (router?.params) {
            getTitleId();
        }
    }, [router.params]);

    const [startVisible, setStartVisible] = useState(false);
    // 开始绑定子设备
    const bindSubDevice = async (row, actionType = 'bind') => {
        if (userStore.userDeviceYY01Data.length == 0) {
            Toast.show({ content: t('AddDeviceScreen.t55'), layout: 'top' });
            return;
        }
        if (hasPermission) {
            if (deviceStore.device.deviceStatus == 0) {
                Toast.show({ content: t('Acupoints.t18'), layout: 'top' });
                return;
            }
            if (title_id == 0) {
                setStartVisible(true);
            }
            // 获取对应小包
            const { course } = await getWuXueCourseApi({ id: title_id });
            if (course.length == 0) {
                Toast.show({ content: t('AddDeviceScreen.t59') });
                return;
            }
            const result: any = course.find((item: any) => {
                return item.body_index == row.body_index;
            });
            const { status, data } = await getUserArticleListApi();
            if (status !== 1) {
                Toast.show({ content: t('AddDeviceScreen.t58') });
                return;
            }
            const res: any = data.find((item: any) => {
                return String(item.title_id) === String(title_id);
            }) || { id: '' };
            if (!res.id && actionType == 'bind') {
                Toast.show({ content: t('AddDeviceScreen.t58') });
                return;
            }

            const hasLocationPermissions = await checkAndRequestLocationPermissions();
            const hasBluetoothPermissions = await checkAndRequestBluetoothPermissions();
            if (!hasLocationPermissions && hasBluetoothPermissions) {
                Toast.show({ content: t('ScanBleDevice.t2'), layout: 'top' });
                return;
            }
            if (deviceStore.device.deviceStatus == 0) {
                Toast.show({ content: t('ScanBleDevice.t3'), layout: 'top' });
                return;
            }
            Bleconnect.scan(5);
            navigation.navigate('ScanBleDevice', {
                routePage: 'Acupoints',
                body_index: actionType == 'unbind' ? 0 : row.body_index,
                course_id: result?.id ? result?.id : '',
                titleId: title_id,
                actionType,
                id: row.id,
                write_id: res.id,
                oldDeviceSn: row.armarium_device_chang,
            });
        } else {
            requestPermission();
        }
    };

    // 查看yy01详情
    const goDetailes = () => {
        navigation.navigate('AcupoinDeviceDetailes', { device_sn });
    };
    // 选择其它yy01设备
    const [visible1, setVisible1] = useState(false);
    const selectDeviceCallBack = (res) => {
        setSelecDevice(res);
    };
    return (
        <View style={styles.container}>
            <NavBarHeader title={t('AddDeviceScreen.title')} />
            <ScrollView contentContainerStyle={styles.contentContainerStyle} showsVerticalScrollIndicator={false}>
                <View style={styles.card}>
                    <View style={[styles.row, styles.between]}>
                        <Text style={styles.title}>{t('AddDeviceScreen.t1')}</Text>
                        {userStore.userDeviceYY01Data.length > 0 && (
                            <Pressable onPress={() => setVisible1(true)}>
                                <Icon name={'reorder-four-outline'} size={px2dp(40)} color={'#666666'}></Icon>
                            </Pressable>
                        )}
                        {userStore.userDeviceYY01Data.length == 0 && (
                            <TouchableOpacity
                                style={styles.bindBt}
                                onPress={() => {
                                    if (hasPermission) {
                                        navigation.navigate('ScanBleDevice');
                                    } else {
                                        requestPermission();
                                    }
                                }}>
                                <Text style={styles.bt_text}>{t('AddDeviceScreen.t14')}</Text>
                            </TouchableOpacity>
                        )}
                    </View>
                    {selectDevice?.device_sn && (
                        <View style={{ justifyContent: 'center', alignItems: 'center' }}>
                            <FastImage
                                style={styles.yy01}
                                source={{
                                    uri: 'https://bjy-crmeb.oss-cn-shenzhen.aliyuncs.com/attach/2025/02/ac25e20250224170209347.png',
                                    priority: FastImage.priority.high,
                                }}
                                resizeMode={FastImage.resizeMode.contain}
                            />
                            <Text style={styles.tips}>{selectDevice.device_sn}</Text>
                            <TouchableOpacity style={styles.bindBt} onPress={goDetailes}>
                                <Text style={styles.bt_text}>{t('AddDeviceScreen.t26')}</Text>
                            </TouchableOpacity>
                        </View>
                    )}
                </View>
                <View style={styles.card1}>
                    <View>
                        <Text style={styles.title}>{t('AddDeviceScreen.t8')}</Text>
                    </View>
                    <Text style={styles.tips}>{t('AddDeviceScreen.t23')}</Text>
                    <View>
                        {deviceList.map((item, index) => {
                            return (
                                <View key={item.id} style={[styles.item, styles.row, styles.between]}>
                                    <View style={[styles.row]}>
                                        <FastImage
                                            style={styles.device_images}
                                            source={{
                                                uri: item.device_image,
                                                priority: FastImage.priority.high,
                                            }}
                                            resizeMode={FastImage.resizeMode.contain}
                                        />
                                        <View style={{ marginLeft: px2dp(24) }}>
                                            <Text style={styles.device_sn}>
                                                {item.armarium_device_chang ? item.armarium_device_chang : '—'}
                                            </Text>
                                            <Text style={styles.name}>{item.name}</Text>
                                            <Text style={[styles.statusColor, item.status !== 1 && { color: 'red' }]}>
                                                {item.status == 1 ? t('AddDeviceScreen.t52') : t('AddDeviceScreen.t53')}
                                            </Text>
                                        </View>
                                    </View>
                                    <View>
                                        {item.armarium_device_chang ? (
                                            <TouchableOpacity
                                                onPress={() => bindSubDevice(item, 'unbind')}
                                                style={[styles.bt1, { backgroundColor: 'rgba(29, 206, 135, 0.12)' }]}>
                                                <Text style={[styles.bt_text1, { color: '#1DCE87' }]}>
                                                    {t('AddDeviceScreen.t29')}
                                                </Text>
                                            </TouchableOpacity>
                                        ) : (
                                            <TouchableOpacity
                                                style={[styles.bt1]}
                                                onPress={() => bindSubDevice(item, 'bind')}>
                                                <Text style={[styles.bt_text1]}>{t('AddDeviceScreen.t20')}</Text>
                                            </TouchableOpacity>
                                        )}
                                    </View>
                                </View>
                            );
                        })}
                    </View>
                </View>
                {/* {!isDeviceSnEmpty && selectDevice.device_sn && (
                    <>
                        {devicesStatus1.length == 5 ? (
                            <TouchableOpacity style={[styles.bindButton, styles.row]} onPress={switchCourse}>
                                <Text style={styles.bt_text}>{t('AddDeviceScreen.t54')}</Text>
                            </TouchableOpacity>
                        ) : (
                            <TouchableOpacity style={[styles.bindButton, styles.row]} onPress={writeCourse}>
                                <Text style={styles.bt_text}>{t('AddDeviceScreen.t22')}</Text>
                            </TouchableOpacity>
                        )}
                    </>
                )} */}
            </ScrollView>
            <UserDeviceListModal
                visible={visible1}
                titleId={title_id}
                onToggleVisible={() => setVisible1(false)}
                callBack={selectDeviceCallBack}
            />
            {/* 这是写入的 */}
            <SelectCourseModal
                visible={startVisible}
                device_sn={device_sn}
                changeTitleId={(id) => {
                    setTitle_id(id);
                    Toast.show({ content: t('AddDeviceScreen.t60'), layout: 'top' });
                }}
                onToggleVisible={() => setStartVisible(false)}
            />
        </View>
    );
});

const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: '#F7F7F7',
    },
    row: {
        flexDirection: 'row',
        alignItems: 'center',
    },
    between: {
        justifyContent: 'space-between',
    },
    header: {
        alignItems: 'center',
        justifyContent: 'center',
        backgroundColor: 'red',
    },
    contentContainerStyle: {
        flexGrow: 1,
        paddingBottom: '30%',
    },
    card: {
        backgroundColor: '#fff',
        zIndex: 99999,
        padding: px2dp(24),
        margin: px2dp(24),
        borderRadius: px2dp(24),
        // minHeight: '36%',
        position: 'relative',
    },
    title: {
        fontSize: scale(30),
        fontWeight: 'bold',
        color: '#1A1A1A',
    },
    cardContent: {
        top: '40%',
        alignSelf: 'center',
    },
    card_icons: {
        height: px2dp(202),
        width: px2dp(172),
        alignSelf: 'center',
    },
    tips: {
        color: '#666666',
        fontSize: scale(28),
        marginTop: px2dp(24),
    },
    modal: {
        flex: 1,
        justifyContent: 'center',
        alignItems: 'center',
        backgroundColor: 'rgba(0, 0, 0, 0.5)',
    },
    modalContainer: {
        width: '90%',
        backgroundColor: 'white',
        borderRadius: 10,
        padding: px2dp(24),
        maxHeight: '60%',
    },
    device_icons: {
        width: px2dp(120),
        height: px2dp(120),
    },
    listItem: {
        marginTop: px2dp(24),
        paddingBottom: px2dp(24),
    },
    deviceName: {
        color: '#000',
        fontSize: scale(26),
        fontWeight: 'bold',
        marginBottom: px2dp(12),
    },
    bt: {
        justifyContent: 'center',
        alignItems: 'center',
        backgroundColor: '#25C8C8',
        height: px2dp(60),
        marginTop: px2dp(32),
        borderRadius: px2dp(100),
        width: px2dp(120),
    },
    bt_text: {
        color: '#fff',
        fontSize: scale(28),
    },
    yy01: {
        width: px2dp(220),
        height: px2dp(220),
    },
    bindBt: {
        justifyContent: 'center',
        alignItems: 'center',
        backgroundColor: '#25C8C8',
        height: px2dp(80),
        marginTop: px2dp(32),
        borderRadius: px2dp(12),
        width: px2dp(220),
    },
    card1: {
        backgroundColor: '#fff',
        padding: px2dp(24),
        marginHorizontal: px2dp(24),
        borderRadius: px2dp(24),
    },
    device_images: {
        width: px2dp(100),
        height: px2dp(100),
    },
    item: {
        marginTop: px2dp(24),
        paddingVertical: px2dp(24),
        borderBottomWidth: onePx,
        borderColor: '#eee',
    },
    device_sn: {
        color: '#000',
        fontWeight: '500',
        fontSize: scale(28),
        marginBottom: px2dp(6),
    },
    name: {
        color: '#a6a6a6',
        fontSize: scale(24),
        marginBottom: px2dp(6),
    },
    statusColor: {
        color: '#1DCE87',
        fontSize: scale(26),
    },
    bt1: {
        backgroundColor: '#1877FF',
        borderRadius: px2dp(40),
        paddingHorizontal: px2dp(20),
        paddingVertical: px2dp(10),
    },
    bt_text1: {
        fontSize: scale(24),
        color: '#fff',
        fontWeight: 'bold',
    },
    bindButton: {
        justifyContent: 'center',
        backgroundColor: '#1877FF',
        height: px2dp(96),
        marginTop: px2dp(32),
        borderRadius: px2dp(16),
        marginHorizontal: px2dp(24),
    },
});
